package com.epoint.netty.chat.handler;

import com.epoint.netty.chat.message.LoginRequestMessage;
import com.epoint.netty.chat.message.LoginResponseMessage;
import com.epoint.netty.chat.server.service.UserServiceMemoryImpl;
import com.epoint.netty.chat.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage loginRequestMessage) throws Exception {
        UserServiceMemoryImpl userServiceMemory = new UserServiceMemoryImpl();
        boolean login = userServiceMemory.login(loginRequestMessage.getUsername(), loginRequestMessage.getPassword());
        LoginResponseMessage loginResponseMessage = new LoginResponseMessage();
        loginResponseMessage.setSuccess(login);
        if(login){
            SessionFactory.getSession().bind(ctx.channel(), loginRequestMessage.getUsername());
        }
        ctx.writeAndFlush(loginResponseMessage);
    }
}
